package com.inplaceedit.client.ui;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.Command;

public class SaveCancelDialogAdapter implements SaveCancelDialog {

	public static SaveCancelDialog of(final Command showCommand,
			final Command hideCommand, final HasClickHandlers saveCommand,
			final HasClickHandlers cancelCommand) {

		return new SaveCancelDialogAdapter(showCommand, hideCommand, saveCommand,
				cancelCommand);
	}

	private final Command showCommand;
	private final Command hideCommand;
	private SaveCancelDialog.Handler handler;

	private SaveCancelDialogAdapter(final Command showCommand,
			final Command hideCommand, final HasClickHandlers saveCommand,
			final HasClickHandlers cancelCommand) {

		this.showCommand = showCommand;
		this.hideCommand = hideCommand;

		saveCommand.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(final ClickEvent event) {
				if (handler != null) {
					handler.onSave();
				}
			}
		});
		cancelCommand.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(final ClickEvent event) {
				if (handler != null) {
					handler.onCancel();
				}
			}
		});
	}

	@Override
	public void hide() {
		hideCommand.execute();
		handler = null;
	}

	@Override
	public void show(final Handler handler) {
		this.handler = handler;
		showCommand.execute();
	}
}
